package com.tonicgb.shared.util;


import com.tonicgb.shared.exception.ApiException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;

/**
 * @author zhaiyujin
 * @date 2021-09-06 23:54:08
 * @说明 密码加解密工具类
 */
public class SecurityUtil {



    public static String encryptPassword(String pwd, String key){
        try {

            Key _key = getDESSercretKey(key);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, _key);
            byte[] data = pwd.getBytes(StandardCharsets.UTF_8);
            byte[] result = cipher.doFinal(data);
            //jdk1.8
            // return new sun.misc.BASE64Encoder().encode(result);
            //jdk11
            byte[] r=  Base64.getMimeEncoder().encode(result);
            return new String(r, StandardCharsets.UTF_8);
        }catch (Exception e){
            throw new ApiException("密码处理异常");
        }
    }

    /**
     * 解密密码
     */
    public static String decryptPassowrd(String pwd, String key)
            throws Exception {

        Key aKey = getDESSercretKey(key);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, aKey);
        //jdk11
        byte[] data= Base64.getMimeDecoder().decode(pwd);
        //jdk1.8
        //byte[] data = new sun.misc.BASE64Decoder().decodeBuffer(pwd);
        byte[] result = cipher.doFinal(data);

        return new String(result, StandardCharsets.UTF_8);
    }

    /**
     * 获得DES加密秘钥
     * @param key
     * @return
     * @throws UnsupportedEncodingException
     */
    public static SecretKey getDESSercretKey(String key) throws UnsupportedEncodingException {
        byte[] result = new byte[8];
        byte[] keys = null;
        keys = key.getBytes(StandardCharsets.UTF_8);
        for(int i = 0; i<8;i++){
            if(i < keys.length){
                result[i] = keys[i];
            }else{
                result[i] = 0x01;
            }
        }
        return new SecretKeySpec(result, "DES");
    }


}
